/*
 * JSFConsole - Lightweight JSF Application Monitor
 * Copyright (C) 2009  Grzegorz Bugaj
 * http://www.gregbugaj.com
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/
package com.gregbugaj.jsfconsole.util.reflection;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;

import com.gregbugaj.jsfconsole.util.ReflectUtil;

/**
 * Reflection provider that confirms to java bean naming convention for
 * object introspection
 * @author devil
 *
 */
public class BeanReflectionProvider implements ReflectionProviderStrategy {

	
	public Field getAccesibleField(String fieldName, Object obj) {
		for(Class<?> superClazz=obj.getClass(); superClazz!=Object.class; superClazz=superClazz.getSuperclass()){		
			for(Field field : superClazz.getDeclaredFields()){
				if(Modifier.isTransient(field.getModifiers()) 
						|| !ReflectUtil.makeAccessible(field)
						|| !hasGetterMethod(field, obj)
				){
					continue;
				}
				if(field.getName().equals(fieldName)){					
					return field;
				}
			}
		}
		return null;
	}

	/**
	 * Find all fields that can be inspected for given object, this include private objects as long
	 * as they have a associated getter method that meets with the bean specification
	 * object with transient fields will by skipped
	 * @param obj to inspect
	 * @return list of fields
	 */
	
	public List<Field> getAccesibleFields(Object obj) {
		List<Field> items=new ArrayList<Field>();
		for(Class<?> superClazz=obj.getClass(); superClazz!=Object.class; superClazz=superClazz.getSuperclass()){		
			for(Field field : superClazz.getDeclaredFields()){
				if(Modifier.isTransient(field.getModifiers()) 
						|| !ReflectUtil.makeAccessible(field)
						|| !hasGetterMethod(field, obj)
				){
					continue;
				}
				items.add(field);			
			}
		}
		return items;
	}

	/**
	 * Only process is/get methods without any parameters		
	 * @param o
	 * @return list of methods matching our criteria
	 */
	
	public List<Method> getMethods(Class<?> clazz) {
		List<Method> items=new ArrayList<Method>();
		for(Class<?> superClazz=clazz;superClazz!=Object.class; superClazz=superClazz.getSuperclass()){
			for(Method method : superClazz.getDeclaredMethods()){	
				if(method.isSynthetic() || 
						Modifier.isPrivate(method.getModifiers()) ||
						Modifier.isProtected(method.getModifiers()) ||
						method.getParameterTypes().length!=0 ||
						method.getReturnType() == Void.TYPE	||
						Modifier.isStatic(method.getModifiers()) ||
						!isValidBeanMethod(method)		
				)
				{
					continue;
				}

				items.add(method);
			}
		}
		return items;
	}

	private boolean isValidBeanMethod(Method method) {
		String methodName=method.getName();
		return methodName.startsWith("get") || methodName.startsWith("is");
	}

	/**
	 * Check if given object has getter method in the given object
	 * getter method for a boolean CAN be getField() and isField() but for
	 * the EJB spec they need to be isField so thats what we are looking for
	 * @param field to check
	 * @param obj to check on
	 * @return true if there is getter otherwise false
	 */
	private  boolean hasGetterMethod(Field field, Object obj) {
		boolean isBoolean = isBooleanField(field);
		for(Class<?> superClazz=obj.getClass(); superClazz!=Object.class; superClazz=superClazz.getSuperclass()){		
			for(Method method : superClazz.getDeclaredMethods()){
				String getterName=getGetterName(field.getName(), false);
				if(isBoolean){
					getterName=getGetterName(field.getName(), true);
				}
				if(getterName.equals(method.getName())){
					return true;
				}
			}
		}
		return false;
	}


	private static String getGetterName(String propertyName, boolean isBoolean) {
		String propConverted=propertyName.substring(0, 1).toUpperCase()+propertyName.substring(1);
		String prefix="get";
		if(isBoolean){
			prefix="is";
		}
		propConverted=prefix+propConverted;
		return propConverted;
	}

	/**
	 * Check if a field is a boolean field
	 * @param field
	 * @return
	 */
	private static boolean isBooleanField(Field field) {
		boolean isBooleanField=false;
		try {
			isBooleanField=(field.getType() == boolean.class || field.getType() == Boolean.class);
		} catch (Exception e) {
			isBooleanField=false;
		} 
		return isBooleanField;
	}
}
